package com.example.flybird.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;

import com.example.flybird.App;
import com.example.flybird.utils.SoundUtils;
import com.example.flybird.R;
import com.example.flybird.dao.LeaderboardDAO;
import com.example.flybird.model.Leaderboard;
import com.example.flybird.utils.Draw;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;


public class Fly extends Activity{

    int points;
    boolean iswaste;
    boolean flag;
    int bird = 0;
    /**屏幕高度*/
    int screenHeight;
    /**屏幕宽度*/
    int screenWidth;

    /**横向坐标*/
    int qiu_x = 100;
    int qiu_y;

    int qiu_size = 50;

    int zhu_height1;
    int zhu_height2;
    int zhu_width1;
    int zhu_width2;
    int zhu_x1;
    int zhu_x2;
    int zhu_y1;
    int zhu_y2;

    /**球下降速度*/
    int qiu_downspeed = 3;
    /**球上升速度*/
    int qiu_upspeed = 70;
    /**柱子移动速度*/
    int zhu_xspeed = 5;


    public static Handler handler;
    MyGameView gameview;
    ScheduledExecutorService service;
    AlertDialog.Builder ab;
    SoundUtils soundUtils;
    AlertDialog dialog;
    App app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去掉窗口标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //使程序全屏显示
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        //创建自定义的GameView组件
        gameview = new MyGameView(this);
        setContentView(gameview);
        app = (App) getApplication();
        //获取窗口管理器
        WindowManager wind = getWindowManager();
        Display display = wind.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        //TODO
        //获取屏幕宽 高
        screenHeight = metrics.heightPixels;
        screenWidth = metrics.widthPixels;

        //创建音效实例
        soundUtils = new SoundUtils(Fly.this, SoundUtils.RING_SOUND);

        //设置两根柱子的初始位子
        //新
        zhu_height1 = (int) (Math.random() * (screenHeight - 199));
        zhu_width1 = (int) (100 + Math.random() * 301);
        zhu_x1 = screenWidth;
        zhu_y1 = 0;

        zhu_height2 = screenHeight - zhu_height1 - 200;
        zhu_width2 = zhu_width1;
        zhu_x2 = screenWidth;
        zhu_y2 = screenHeight;


        //球初始y位置
        qiu_y = screenHeight >> 1;

        //初始分数
        points = 0;

        //初始分数标识
        flag = true;

        handler = new Handler(Looper.myLooper()) {
            @Override
            public void dispatchMessage(@NonNull Message msg) {
                super.dispatchMessage(msg);
                if (msg.what == 0x123) {
                    gameview.invalidate();
                }
                if (msg.what == 0x333) {
                    gameview = new MyGameView(Fly.this);
                    Fly.this.setContentView(gameview);
                    play();
                }
            }
        };
        //游戏开始
        play();

    }
    @SuppressLint("ClickableViewAccessibility")
    public void play(){

        iswaste = false;

        //柱子初始位置 长宽 [0,screen_height-200] [100,400]
        zhu_height1 = (int) (Math.random() * (screenHeight - 199));
        zhu_width1 = (int) (100 + Math.random() * 301);
        zhu_x1 = screenWidth;
        zhu_y1 = 0;

        zhu_height2 = screenHeight - zhu_height1 - 200;
        zhu_width2 = zhu_width1;
        zhu_x2 = screenWidth;
        zhu_y2 = screenHeight;

        //球初始y位置
        qiu_y = screenHeight >> 1;

        //初始分数
        points = 0;

        //初始分数标识
        flag = true;


        //重写手势识别
        gameview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int startX;
                int startY;
                switch(event.getAction()){
                    case MotionEvent.ACTION_DOWN: // 用户手指按下事件
                        //开始播放音效
                        soundUtils.putSound(1, R.raw.btn_yin);
                        soundUtils.playSound(1, SoundUtils.SINGLE_PLAY);
                        //用户手指按下时上升小球高度
                        qiu_y = qiu_y - qiu_upspeed;

                        break;
                    case MotionEvent.ACTION_MOVE: // 用户手指滑动事件
                        break;
                    case MotionEvent.ACTION_UP: //用户手指抬起事件
                        break;
                    default:{

                    }
                }
                //通知gameView组件从新绘制
                gameview.invalidate();
                return true;
            }
        });

        //创建一个定时器实例
        service = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r);
            }
        });
        service.scheduleWithFixedDelay(new TimerTask() {
            public int p = 0;
            @Override
            public void run() {


                //球与柱的位置变化
                qiu_y = qiu_y + qiu_downspeed;
                zhu_x1 = zhu_x1 - zhu_xspeed;
                zhu_x2 = zhu_x2 - zhu_xspeed;

                //球碰撞柱子
                if (qiu_x + 15 >= zhu_x1 && qiu_x - 15 <= zhu_x1 + zhu_width1) {
                    if (qiu_y - 15 <= zhu_height1 || qiu_y + 15 >= zhu_height1 + 200) {
                        iswaste = true;
                        service.shutdown();
                    }
                }

                //球碰撞屏幕上下边缘
                if (qiu_y + 15 >= screenHeight || qiu_y - 15 <= 0) {
                    iswaste = true;
                    //开始播放音效
                    soundUtils.putSound(2, R.raw.wang_yin);
                    soundUtils.playSound(2, SoundUtils.SINGLE_PLAY);
                    service.shutdown();
                    //timer.cancel();
                }

                //积分判断
                if (flag) {
                    if (qiu_x - 15 > zhu_x1 + zhu_width1) {
                        points++;
                        flag = false;
                    }
                }

                //柱子右侧移出左屏幕时，柱子回档到右屏幕，作为下一个柱子
                if (zhu_x1 + zhu_width1 <= 0) {
                    //下一个柱子x坐标
                    zhu_x1 = screenWidth;
                    zhu_x2 = screenWidth;
                    zhu_xspeed+=1;//柱子移动速度递增

                    //下一个柱子随机长 宽
                    zhu_height1 = (int) (Math.random() * (screenHeight - 199));
                    zhu_width1 = (int) (100 + Math.random() * 301);

                    zhu_height2 = screenHeight - zhu_height1 - 200;
                    zhu_width2 = zhu_width1;

                    flag = true;
                }
                //发送空消息，通知游戏组件重新绘制
                handler.sendEmptyMessage(0x123);
            }
        },0,15, TimeUnit.MILLISECONDS);
    }

    class MyGameView extends View {
        //创建一支画笔实例
        Paint paint = new Paint();
        public MyGameView(Context context) {
            super(context);
        }
        //重现onDraw方法进行绘图
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            //设置画笔样式
            paint.setStyle(Paint.Style.FILL);
            //设置画笔抗锯齿
            paint.setAntiAlias(true);
            //判断游戏是否结束
            if(iswaste){
                service.shutdown();
                //游戏结束后执行的内容
                Fly.this.setContentView(R.layout.item_view);
                TextView textView = (TextView) Fly.this.findViewById(R.id.item_view);
                Button btn_1 = (Button) Fly.this.findViewById(R.id.item_btn_1);
                Button btn_3 = (Button) Fly.this.findViewById(R.id.item_btn_3);
                Button btn_4 = (Button) Fly.this.findViewById(R.id.item_btn_4);
                btn_1.setOnClickListener(click);
                btn_3.setOnClickListener(click);
                btn_4.setOnClickListener(click);
                textView.setText("本次获得："+points+"分");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Sichuan"));
                final LeaderboardDAO leaderboardDAO = new LeaderboardDAO(Fly.this);
                Leaderboard leaderboard = new Leaderboard(UUID.randomUUID().toString(), app.getName(), points, dateFormat.format(new Date()));
                leaderboardDAO.add(leaderboard);
            }else{

                //画背景
                Draw.DrawBitmap(getResources(), R.drawable.image_1, 0, 0, screenWidth, screenHeight, canvas);

                //画球
                if (bird == 0) {
                    Draw.DrawBitmap(getResources(), R.drawable.bird_0, qiu_x - qiu_size, qiu_y - qiu_size, qiu_x + qiu_size, qiu_y + qiu_size, canvas);
                    bird=1;
                } else if (bird == 1) {
                    Draw.DrawBitmap(getResources(), R.drawable.bird_1, qiu_x - qiu_size, qiu_y - qiu_size, qiu_x + qiu_size, qiu_y + qiu_size, canvas);
                    bird=2;
                } else if (bird == 2) {
                    Draw.DrawBitmap(getResources(), R.drawable.bird_2, qiu_x - qiu_size, qiu_y - qiu_size, qiu_x + qiu_size, qiu_y + qiu_size, canvas);
                    bird=0;
                }

                //画柱子
                Draw.DrawBitmap(getResources(), R.drawable.pipe_up, zhu_x1, zhu_y1, zhu_x1 + zhu_width1, zhu_y1 + zhu_height1, canvas);
                Draw.DrawBitmap(getResources(), R.drawable.pipe_down, zhu_x2, zhu_y2 - zhu_height2, zhu_x2 + zhu_width2, zhu_y2, canvas);

                //画分数
                paint.setColor(Color.RED);
                paint.setTextSize(80);
                paint.setTextAlign(Paint.Align.CENTER);
                canvas.drawText(points + "", screenWidth >> 1, 80, paint);
            }
        }
    }


    View.OnClickListener click = new View.OnClickListener() {
        @SuppressLint("NonConstantResourceId")
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.item_btn_1) {
                //开始播放音效
                soundUtils.putSound(0, R.raw.btn_yin);
                soundUtils.playSound(0, SoundUtils.SINGLE_PLAY);
                handler.sendEmptyMessage(0x333);
            }else if (v.getId() == R.id.item_btn_3) {
                //开始播放音效
                soundUtils.putSound(0, R.raw.btn_yin);
                soundUtils.playSound(0, SoundUtils.SINGLE_PLAY);
                Intent it = new Intent(Fly.this, PersonalRecord.class);
                startActivity(it);
            }else if (v.getId() == R.id.item_btn_4){
                Intent intent = new Intent(Fly.this, MainActivity.class);
                startActivity(intent);
            }
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        soundUtils.stop();
    }

}
